//
//  YTSite.m
//  YuTouSeeder
//
//  Created by Huang Dong on 10-9-23.
//  Copyright 2010 limboworks.com. All rights reserved.
//

#import "YTSite.h"


@implementation YTSite

@synthesize error;
@synthesize result;


-(id)init{
	[super init];
	loginURL = [[NSURL URLWithString:@"http://tianyutou.com/api/v1/login"] retain];
	checkinURL = [[NSURL URLWithString:@"http://tianyutou.com/api/v1/checkin"] retain];
	
	cookies = [[NSMutableArray alloc] init];
	islogin=NO;
	self.error=@"";
	return self;
}

-(void)dealloc{
	[cookies release];
	[loginURL release];
	[checkinURL release];
	[error release];
	[super dealloc];
}

-(BOOL)loginByUsername:(NSString *)userName PassWord:(NSString *)passWord{
	NSLog(@"Login to Yutou Site...");
	ASIFormDataRequest *request;
	request = [ASIFormDataRequest requestWithURL:loginURL];
	[request addRequestHeader:@"User-Agent" value:@"YuTouPush-Agent-1.0"];
	[request setPostValue:userName forKey:@"email"];
	[request setPostValue:passWord forKey:@"password"];
	[request startSynchronous];
	
	NSError *returnerror = [request error];
	if (returnerror) {
		self.error=[returnerror localizedDescription];
		NSLog(@"login error:%@",returnerror);
		return NO;
	}
	[cookies setArray:[request responseCookies]];
	
	NSDictionary *jsonArray =[[request responseString] JSONValue];
	NSLog(@"json is:%@",jsonArray);	
	
	statuscode = [jsonArray valueForKey:@"status_code"];
	success = [[jsonArray valueForKey:@"success"] boolValue];
	if (success) {
		self.result = [[jsonArray valueForKey:@"result"] valueForKey:@"result"];
		NSLog(@"result:%@",self.result);
		self.error=[[jsonArray valueForKey:@"result"]valueForKey:@"error"];
		NSLog(@"error:%@",self.error);
		
		if ([self.result boolValue]) {
			islogin=YES;
			return YES;
		}
	}
	islogin=NO;
	return NO;
	
}

-(BOOL)checkinVerb:(NSString *)verb Noun:(NSString *)noun Location:(NSString *)location{
	NSLog(@"Checkin to Yutou Site...");
	ASIFormDataRequest *request;
	request = [ASIFormDataRequest requestWithURL:checkinURL];
	[request addRequestHeader:@"User-Agent" value:@"YuTouPush-Agent-1.0"];
	[request setPostValue:verb forKey:@"verb"];
	[request setPostValue:noun forKey:@"noun"];
	[request setPostValue:location forKey:@"location"];
	[request startSynchronous];
	
	NSError *returnerror = [request error];
	if (returnerror) {
		self.error=[returnerror localizedDescription];
		NSLog(@"login error:%@",returnerror);
		return NO;
	}
	[cookies setArray:[request responseCookies]];

	
	NSDictionary *jsonArray =[[request responseString] JSONValue];
	NSLog(@"json is:%@",jsonArray);	
	
	statuscode = [jsonArray valueForKey:@"status_code"];
	success = [[jsonArray valueForKey:@"success"] boolValue];
	return success;
}

@end
